<template>
  <!-- 2. 准备具备宽高的DOM容器 -->
  <div :style="{ width, height }" ref="chartRef"></div>
</template>

<script lang="ts" setup>
// 1. 引入echarts
// 完整引入，体积太大
// import type { EChartsOption } from "echarts";
// 按需引入
import echarts, { ECOption } from "@/utils/echarts";
import { onMounted, ref, onBeforeUnmount, watch } from "vue";
import debounce from "lodash/debounce"; // declare module "lodash/debounce";

defineOptions({
  name: "Chart",
});

const props = withDefaults(
  defineProps<{
    width?: string;
    height?: string;
    option: ECOption;
  }>(),
  {
    width: "100%",
    height: "100%",
  }
);

const chartRef = ref();

let myEcharts: echarts.ECharts;

onMounted(() => {
  // 3. 初始化echarts实例
  // 问题：1，直接操作DOM不好 2. 将来组件复用只能找到第一个chart-container，只有第一个图表会生成
  // const myEcharts = echarts.init(document.querySelector(".chart-container"));
  myEcharts = echarts.init(chartRef.value);
  // 4. 定义option
  // const option = {};
  // 5. 调用setOption渲染图表
  myEcharts.setOption(props.option);
});

watch(props.option, () => {
  myEcharts.setOption(props.option);
});

const handleResize = debounce(() => {
  myEcharts.resize({
    animation: {
      duration: 300,
    },
  });
}, 200);

onMounted(() => {
  // 浏览器窗口大小调整事件
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="scss"></style>
